<template>
  <div>
    <!-- 正常售卖 -->
    <div v-if="goodsFrom.goodsFlag !== 1" class="box">
      <img :src="goodsFrom.goodsImg" class="goodsImg" @mousemove="move" @mouseover="enter" @mouseout="leave">
      <div class="bigImg" @mouseover="enter" @mouseout="leave" />
      <div class="smallbox" />
      <i class="el-icon-search" />
      <span>
        <el-tag v-if=" goodsUserFrom.complain !== 1" type="primary">{{ goodsUserFrom.username }}用户信誉良好</el-tag>
        <el-tag v-else-if="goodsUserFrom.message =='经过核实，该用户确实违规，目前已被禁用'" type="danger">{{ userList[0].username }}用户已被禁用</el-tag>
        <el-tag v-else type="warning">{{ goodsUserFrom.username }}用户被举报过</el-tag>
        <span><router-link :to=" {path:'/shopping/home', query:{userId} }" target="_blank"><img :src="goodsUserFrom.avatar" class="useravatar" :title="goodsUserFrom.username" @mouseenter="getUserId"></router-link></span>
        <span class="goodsName">{{ goodsFrom.goodsName }}</span>
      </span>
      <span class="goodsDesc">
        商品描述:{{ goodsFrom.goodsDesc }}
      </span>
      <span class="goodsPrice">
        价格:{{ goodsFrom.goodsPrice }}元
      </span>
      <span class="goodsNum">
        库存: {{ goodsFrom.goodsNum }}
      </span>
      <div v-if="buyerUserFrom.username !== goodsUserFrom.username">
        <span class="goodsCount">
          <el-input-number v-model="goodsFrom.goodsCount " round :min="1" :max="goodsFrom.goodsNum" size="small" @change="changebtn" />
          <el-button size="small" class="el-icon-plus" round @click="addGoodsInCart(goodsFrom.goodsId)">购物车</el-button>
        </span>
        <el-card class="desc">
          另一种交易方式:<br><p>可以双方进行沟通需要交换的物品，只有卖方同意，订单才生效!</p>
        </el-card>
        <span class="btn-exchange">
          <el-button round @click="exchangeGoods">尝试换购</el-button>
        </span>
      </div>
      <div class="line" />
      <span class="other">该用户的其他商品</span>
      <ul class="otherGoods">
        <!-- eslint-disable-next-line vue/no-use-v-if-with-v-for -->
        <li v-for="item in goodsList.slice(0, 4)" v-if="item.goodsId !== goodsFrom.goodsId" :key="item.goodsId">
          <img :src="item.goodsImg" @click="changeGoods(item.goodsId)">
        </li>
      </ul>
    </div>
    <!-- 已经售完 -->
    <div v-else class="box">
      <img :src="goodsFrom.goodsImg" class="goodsImg" @mousemove="move" @mouseover="enter" @mouseout="leave">
      <div class="bigImg" @mouseover="enter" @mouseout="leave" />
      <div class="smallbox" />
      <i class="el-icon-search" />
      <span>
        <el-tag v-if=" goodsUserFrom.complain !== 1" type="primary">{{ goodsUserFrom.username }}用户信誉良好</el-tag>
        <el-tag v-else-if="goodsUserFrom.message =='经过核实，该用户确实违规，目前已被禁用'" type="danger">{{ goodsUserFrom.username }}用户已被禁用</el-tag>
        <el-tag v-else type="warning">{{ goodsUserFrom.username }}用户被举报过</el-tag>
        <span><router-link :to=" {path:'/shopping/home', query:{userId} }" target="_blank"><img :src="goodsUserFrom.avatar" class="useravatar" :title="goodsUserFrom.username" @mouseenter="getUserId"></router-link></span>
        <span class="goodsName">{{ goodsFrom.goodsName }}</span>
      </span>
      <span class="goodsDesc">
        商品描述:{{ goodsFrom.goodsDesc }}
      </span>
      <span class="goodsPrice">
        价格:{{ goodsFrom.goodsPrice }}元
      </span>
      <span class="goodsNum">
        库存: 0
      </span>
      <span class="selled">
        <el-tag type="warning">已经售空</el-tag>
      </span>
      <div class="line" />
      <span class="other">该用户的其他商品</span>
      <ul class="otherGoods">
        <!-- eslint-disable-next-line vue/no-use-v-if-with-v-for -->
        <li v-for="item in goodsList.slice(0, 4)" v-if="item.goodsId !== goodsFrom.goodsId" :key="item.goodsId">
          <img :src="item.goodsImg" @click="changeGoods(item.goodsId)">
        </li>
      </ul>
    </div>
    <!-- 留言板 -->
    <div class="chat">
      <ul class="p">
        <li class="p1">留言</li>
        <li class="p2">{{ goodsFrom.chatCount - 1 }}</li>
        <img class="selfavatar" :src="buyerUserFrom.avatar" alt="">
        <textarea v-model="chat" round class="chatInput" placeholder="留下些看法和意见吧" @blur="changeBlur" @focus="changeFocus" />
        <button class="chatBtn" type="primary" @click="send">发送</button>
      </ul>
      <!-- 弹框 -->
      <div v-if="titleUsername !== buyerUserFrom.username" class="userinfobox" @mouseenter="continueUserInfo" @mouseleave="closeUserInfo">
        <div><img src="../../assets/星球.jpg"></div>
        <div class="info">
          <img :src="srcUrl" alt="">
          <div class="username">{{ titleUsername }}(陌生人)</div>
          <div class="button">
            <el-button type="primary">加好友</el-button>
            <router-link :to="{path:'/shopping/chat', query: {userId} }" target="_blank"> <el-button>发消息</el-button></router-link>
          </div>
        </div>
      </div>
      <div v-else class="userinfobox" @mouseenter="continueUserInfo" @mouseleave="closeUserInfo">
        <div><img src="https://gss0.baidu.com/-Po3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/c2fdfc039245d68837bd625aa2c27d1ed31b2495.jpg"></div>
        <div class="info">
          <img :src="srcUrl" alt="">
          <div class="username">{{ titleUsername }}(自己)</div>
          <div class="button">
            <el-button type="primary" @click="selfSkit">进入主页</el-button>
          </div>
        </div>
      </div>
      <!-- 打印留言 -->
      <ul class="chatlist">
        <!-- eslint-disable-next-line vue/no-use-v-if-with-v-for -->
        <li v-for="(item,index) in msg" v-if="index !== 0" :key="index">
          <router-link :to="{path:'/shopping/home', query: {userId} }" target="_blank"><img class="chatavatar" :title="chatUsername[index]" :src="chatAvatar[index]" @mouseleave="closeUserInfo" @mouseenter="openUserInfo"></router-link>
          <div class="infobox">
            <span class="chatusername">{{ chatUsername[index] }}</span>
            <span class="chatinfo">{{ chatInfo[index] }}</span>
          </div>
          <div class="otherinfo">
            <span class="time">{{ chatTime[index] }}</span>
            <span class="agree">
              <img :title="index" src="https://ts1.cn.mm.bing.net/th/id/R-C.7c495de85f140938137168e370bf8962?rik=LOYPbhxwZX%2fmJg&riu=http%3a%2f%2fwww.kuaipng.com%2fUploads%2fpic%2fw%2f2020%2f03-21%2f75556%2fwater_75556_698_698_.png&ehk=v6zbdsn6CEorBRWAply18PVL0Mr7c4fWuEcr3GCRh6I%3d&risl=&pid=ImgRaw&r=0" alt="" @click="countAdd">
              <span class="goodcount"> {{ chatGood[index] }}</span>
              <img :title="index" src="https://ts1.cn.mm.bing.net/th/id/R-C.9f3fa141873358b381dcd474d5f48ef5?rik=tcqqJzjt%2fimlbw&riu=http%3a%2f%2fpic.616pic.com%2fys_img%2f00%2f53%2f14%2f8LcR4OKMAX.jpg&ehk=RGhOqvPDJYD9govSfJGk1v6cU8Jx9vmsfsp8ECekEa4%3d&risl=&pid=ImgRaw&r=0" alt="" @click="countbad">
              <span class="badcount">{{ chatBad[index] }}</span>
            </span>
          </div>
          <div class="hr"><hr></div>
        </li>
      </ul>
    </div>
    <!-- 购物车图标 -->
    <div class="top">
      <el-button type="info" icon="el-icon-upload2" size="mini" @click="returnTop">顶部</el-button>
    </div>
    <div class="cart">
      <el-dropdown>
        <el-button v-if="count === 0" class="btn-buy" icon="el-icon-goods" type="primary" plain @click="open">
          <i class="sum">{{ count }}</i>
        </el-button>
        <el-button v-else class="btn-buy" icon="el-icon-goods" type="primary" @click="handle">
          <i class="sum">{{ count }}</i>
        </el-button>
        <el-dropdown-menu v-if="count != 0 " slot="dropdown" class="buyitem">
          <!-- eslint-disable-next-line vue/no-use-v-if-with-v-for -->
          <el-card v-for="(item, index) in cartList" v-if="item.goodsBuyer === name && item.goodsFlag === 0 " :key="item.goodsId">
            <img class="cart-img" :src="item.goodsImg" alt="">
            <el-tag>{{ index }}</el-tag>
            <el-tag>物品:{{ item.goodsName }}</el-tag>
            <el-tag>发布者:{{ item.goodsOwner }}</el-tag>
            <el-tag>价格:{{ item.goodsPrice.toFixed (2) }} * {{ item.goodsCount }}</el-tag>
            <el-tag>总数: {{ item.goodsNum }}
              <el-input-number v-model="item.goodsCount " :min="1" :max="item.goodsNum" size="mini" @change="changebtn" />
            </el-tag>
            <el-button type="danger" icon="el-icon-delete" size="min" style="float: right;" @click="deleteCart(item.goodsId)" />
          </el-card>
          <el-card v-if="count != 0 ">
            总价: {{ priceSum.toFixed (2) }}
            <el-button type="primary" style="float: right;" @click="handle">去购物车</el-button>
          </el-card>
        </el-dropdown-menu>
      </el-dropdown>
    </div>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import goodsApi from '@/api/goodsManage'
import userApi from '@/api/userManage'
import cartApi from '@/api/cartManage'
export default {
  data() {
    return {
      goodsList: [],
      cartList: [],
      goodsFrom: {},
      userList: [],
      goodsUserFrom: {},
      buyerUserFrom: {},
      goodsInCartFrom: {},
      detaiGoodsId: this.$route.query.detaiGoodsId,
      count: 0,
      priceSum: 0,
      timer: 0,
      mx: 0,
      my: 0,
      boxY: 0,
      chat: '',
      msg: [],
      tmp: [],
      chatAvatar: [],
      chatUsername: [],
      chatInfo: [],
      chatTime: [],
      chatGood: [],
      chatBad: [],
      titleUsername: '',
      srcUrl: '',
      userId: ''
    }
  },
  computed: {
    ...mapGetters([
      'id',
      'name'
    ])
  },
  created() {
    this.getDetaiGoodsById(this.detaiGoodsId)
    setTimeout(this.render, 200)
  },
  methods: {
    // 换购
    exchangeGoods() {
      this.$set(this.goodsFrom, "chatFlag", 1)
      this.$set(this.goodsFrom, "goodsCount", 1)
      this.$set(this.goodsFrom, "goodsBuyer", this.buyerUserFrom.username)
      this.$set(this.goodsFrom, 'goodsMessage', '换购中')
      goodsApi.updateGoods(this.goodsFrom)
      console.log(this.goodsFrom)
      const routeData = this.$router.resolve({ path: '../shopping/exchange', query: { userId: this.goodsUserFrom.id, goodsId: this.goodsFrom.goodsId }})
      window.open(routeData.href, '_blank')
    },
    // 获取用户物品所属者Id
    getUserId(e) {
      userApi.getUserIdByUsername(e.target.title).then(response => {
        this.userId = response.data
      })
    },
    // 点击跳转用户主页
    selfSkit() {
      this.$router.push('/')
    },
    // 点踩
    countbad(e) {
      console.log(this.chatBad)
      const bad = document.querySelector('.badcount')
      const index = +e.target.title
      console.log(index)
      console.log(bad.innerText)
      this.chatBad[index] = +this.chatBad[index] + 1
      console.log(this.chatGood[index])
      this.chatBad.splice(index, 1, this.chatBad[index])
      console.log(this.chatBad)
      const str1 = this.chatBad.toString()
      this.$set(this.goodsFrom, 'chatBad', str1)
      goodsApi.updateGoods(this.goodsFrom)
      console.log(this.chatBad)
    },
    // 点赞
    countAdd(e) {
      console.log(this.chatGood)
      const good = document.querySelector('.goodcount')
      const index = +e.target.title
      console.log(index)
      console.log(good.innerText)
      this.chatGood[index] = +this.chatGood[index] + 1
      console.log(this.chatGood[index])
      this.chatGood.splice(index, 1, this.chatGood[index])
      console.log(this.chatGood)
      const str1 = this.chatGood.toString()
      this.$set(this.goodsFrom, 'chatGood', str1)
      goodsApi.updateGoods(this.goodsFrom)
      console.log(this.chatGood)
    },
    // 弹框用户信息盒子
    openUserInfo(e) {
      clearTimeout(this.timer)
      const top = e.target.getBoundingClientRect().top
      this.titleUsername = e.target.title
      this.srcUrl = e.target.src
      // 根据用户名拿到用户id
      userApi.getUserIdByUsername(this.titleUsername).then(response => {
        this.userId = response.data
      })
      console.log(e.target)
      if (top > 200) {
        this.boxY = top + document.documentElement.scrollTop - 625
        const userinfobox = document.querySelector('.userinfobox')
        const goodicon = document.querySelector('.goodcount')
        console.log(goodicon.innerText)
        userinfobox.style.display = 'block'
        userinfobox.style.top = this.boxY + 'px'
      } else {
        this.boxY = top + document.documentElement.scrollTop - 350
        const userinfobox = document.querySelector('.userinfobox')
        userinfobox.style.display = 'block'
        userinfobox.style.top = this.boxY + 'px'
      }
    },
    continueUserInfo(e) {
      clearTimeout(this.timer)
      console.log(e.target)
      // const userinfobox = document.querySelector('.userinfobox')
      const userinfobox = document.querySelector('.userinfobox')
      userinfobox.style.display = 'block'
      userinfobox.style.top = this.boxY + 'px'
    },
    closeUserInfo() {
      this.timer = setTimeout(function() {
        const userinfobox = document.querySelector('.userinfobox')
        userinfobox.style.display = 'none'
      }, 200)
    },
    // 获取当前时间
    getCurrentDate() {
      const now = new Date()
      const year = now.getFullYear()
      const month = now.getMonth() + 1
      const day = now.getDate()
      let hour = now.getHours()
      let minute = now.getMinutes()
      hour < 10 ? hour = '0' + hour : hour
      minute < 10 ? minute = '0' + minute : minute
      return year + '-' + month + '-' + day + ' ' + hour + ':' + minute
    },
    // 渲染评论
    render() {
      this.chatAvatar = []
      this.chatUsername = []
      this.chatInfo = []
      this.chatTime = []
      this.chatGood = []
      this.chatBad = []
      this.chatGood = this.goodsFrom.chatGood.split(',')
      this.chatBad = this.goodsFrom.chatBad.split(',')
      console.log(this.chatGood)
      console.log(this.chatBad)
      if (this.goodsFrom.chatMsg !== '') {
        console.log(this.goodsFrom)
        // 取出数据 格式:[头像url , 用户名 , 文字]
        this.msg = this.goodsFrom.chatMsg.split(',').reverse()
        console.log(this.msg)
        for (let i = 0; i <= this.goodsFrom.chatCount - 1; i++) {
          console.log(this.msg[i])
          this.tmp = this.msg[i].split('!')
          console.log(this.tmp)
          this.chatAvatar.push(this.tmp[0])
          this.chatUsername.push(this.tmp[1])
          this.chatInfo.push(this.tmp[2])
          this.chatTime.push(this.tmp[3])
        }
        console.log(this.chatGood)
      }
    },
    // 发送评论
    send() {
      // 存入数据 格式:头像url！用户名！文字,
      if (this.chat !== '') {
        console.log(11)
        this.chat = this.buyerUserFrom.avatar + '!' + this.buyerUserFrom.username +
        '!' + this.chat + '!' + this.getCurrentDate()
        this.goodsFrom.chatMsg = this.goodsFrom.chatMsg.concat(this.chat, ',')
        console.log(this.goodsFrom.chatMsg)
        this.$set(this.goodsFrom, 'chatMsg', this.goodsFrom.chatMsg)
        this.goodsFrom.chatCount++
        this.$set(this.goodsFrom, 'chatCount', this.goodsFrom.chatCount)
        this.chatGood.push(0)
        this.chatBad.push(0)
        const str1 = this.chatGood.toString()
        const str2 = this.chatBad.toString()
        console.log(str1)
        console.log(str2)
        this.$set(this.goodsFrom, 'chatGood', str1)
        this.$set(this.goodsFrom, 'chatBad', str2)
        goodsApi.updateGoods(this.goodsFrom)
        this.chat = ''
        this.msg = []
        console.log(this.goodsFrom.chatGood)
        this.$message({
          type: 'success',
          message: '发送成功'
        })
        setTimeout(this.render, 200)
      }
    },
    // 切换其他物品
    changeGoods(id) {
      goodsApi.getGoodsById(id).then(respose => {
        this.goodsFrom = respose.data
        console.log(this.goodsFrom)
        this.getGoodsInfoByUsername(this.goodsFrom.goodsOwner)
        this.getUserListInfoByOwner(this.goodsFrom.goodsOwner)
        this.getUserFromInfoById(this.id)
        this.detaiGoodsId = id
        this.$router.push(`${this.$route.path}?detaiGoodsId=${id}`)
        setTimeout(this.render, 200)
      })
    },
    // 根据id获得物品
    getDetaiGoodsById(id) {
      goodsApi.getGoodsById(id).then(respose => {
        this.goodsFrom = respose.data
        this.getGoodsInfoByUsername(this.goodsFrom.goodsOwner)
        this.getUserListInfoByOwner(this.goodsFrom.goodsOwner)
        this.getUserFromInfoById(this.id)
        this.getAllCart()
      })
    },
    // 购物车信息
    getAllCart() {
      cartApi.getAllCart().then(response => {
        this.cartList = response.data
        this.priceSum = 0
        this.count = 0
        for (let i = 0; i < this.cartList.length; i++) {
          if (this.cartList[i].goodsBuyer === this.name && this.cartList[i].goodsFlag === 0) {
            this.count += 1
            if (this.cartList[i].goodsCount === 0) {
              this.$set(this.cartList[i], 'goodsCount', 1)
            }
            this.priceSum += this.cartList[i].goodsPrice * this.cartList[i].goodsCount
          }
        }
      })
    },
    // 加入购物车
    addGoodsInCart() {
      cartApi.addCart(this.goodsFrom).then(response => {
        this.$message({
          message: response.message,
          type: 'success'
        })
        this.getAllCart()
      })
      this.$set(this.goodsFrom, 'goodsBuyer', this.name)
      this.$set(this.goodsFrom, 'goodsMessage', '待付款')
      if (this.goodsFrom.goodsBuyer !== this.name || this.goodsFrom.goodsFlag === 0) {
        cartApi.updateCart(this.goodsFrom).then(response => {
          this.getAllCart()
        })
      }
    },
    // 移出购物车
    deleteCart(id) {
      cartApi.deleteCartById(id).then(response => {
        this.$message({
          type: 'success',
          message: response.message
        })
        this.getAllCart()
      })
    },
    // 改变计数器
    changebtn() {
      this.cartList.goodsCount += 1
      this.priceSum = 0
      this.count = 0
      for (let i = 0; i < this.cartList.length; i++) {
        if (this.cartList[i].goodsBuyer === this.name && this.cartList[i].goodsFlag === 0) {
          this.count += 1
          this.priceSum += this.cartList[i].goodsPrice * this.cartList[i].goodsCount
        }
      }
    },
    // 物品所属者个人信息
    getUserListInfoByOwner(username) {
      goodsApi.getUserListInfoByOwner(username).then(respose => {
        this.userList = respose.data
        this.goodsUserFrom = this.userList[0]
      })
    },
    // 购买者的个人信息
    getUserFromInfoById(id) {
      userApi.getUserById(id).then(respose => {
        this.buyerUserFrom = respose.data
      })
    },
    // 物品所属者的所有商品
    getGoodsInfoByUsername(goodsOwnerUsername) {
      goodsApi.getGoodsInfoByUsername(goodsOwnerUsername).then(respose => {
        this.goodsList = respose.data
      })
    },
    // 得到焦点
    changeFocus() {
      const input = document.querySelector('.chatInput')
      const btn = document.querySelector('.chatBtn')
      input.style.height = '80px'
      btn.style.height = '80px'
      input.style.transitionDuration = '0.5s'
      btn.style.transitionDuration = '0.5s'
    },
    // 失去焦点
    changeBlur() {
      const input = document.querySelector('.chatInput')
      const btn = document.querySelector('.chatBtn')
      input.style.height = '50px'
      btn.style.height = '50px'
      input.style.transitionDuration = '0.5s'
      btn.style.transitionDuration = '0.5s'
    },
    // 跳转到购物车页面
    handle() {
      this.$router.push('/shopping/cart')
    },
    // 提示购物车为空
    open() {
      const h = this.$createElement

      this.$notify({
        title: '提示小助手',
        message: h('i', { style: 'color: teal' }, '购物车空空如也~赶紧添加商品到购物车吧！')
      })
    },
    // 返回顶部
    returnTop() {
      let top = document.documentElement.scrollTop || document.body.scrollTop
      // 实现滚动效果
      const timeTop = setInterval(() => {
        document.body.scrollTop = document.documentElement.scrollTop = top -= 50
        if (top <= 0) {
          clearInterval(timeTop)
        }
      }, 10)
    },
    // 放大镜
    // 鼠标移入显示大盒子
    enter(e) {
      clearTimeout(this.timer)
      const big = document.querySelector('.bigImg')
      const small = document.querySelector('.smallbox')
      small.style.display = 'block'
      big.style.display = 'block'
      big.style.backgroundImage = `url(${this.goodsFrom.goodsImg})`
    },
    // 鼠标移出隐藏大盒子
    leave() {
      this.timer = setTimeout(() => {
        const big = document.querySelector('.bigImg')
        const small = document.querySelector('.smallbox')
        small.style.display = 'none'
        big.style.display = 'none'
      }, 200)
    },
    // 黑色遮罩层跟着移动
    move(e) {
      const small = document.querySelector('.smallbox')
      const big = document.querySelector('.bigImg')
      const x = e.pageX - e.target.getBoundingClientRect().left
      const y = e.pageY - e.target.getBoundingClientRect().top - document.documentElement.scrollTop
      this.mx = 0
      this.my = 0
      if (x < 87.5) this.mx = 0
      else if (x >= 87.5 && x <= 262.5) this.mx = x - 100
      else this.mx = 175
      if (y < 87.5) this.my = 0
      else if (y >= 87.5 && y <= 262.5) this.my = y - 100
      else this.my = 175
      small.style.left = this.mx + 'px'
      small.style.top = this.my + 'px'
      big.style.backgroundPositionX = -2 * this.mx + 'px'
      big.style.backgroundPositionY = -2 * this.my + 'px'
    }
  }

}
</script>

<style src="../../styles/detaiGoods.css" scoped>

</style>
